package cn.hh.wechatkit.api.jssdk;

import cn.hh.wechatkit.exception.Wx_Exception_InvalidJsonParse;
import cn.hh.wechatkit.exception.Wx_Exception_InvalidResponse;
import cn.hh.wechatkit.param.WxParam;
import cn.hh.wechatkit.pojo.token.WxToken_JsApiToken;
import cn.hhchat.kit.http.httpUtil;
import com.alibaba.fastjson.JSON;
import okhttp3.Headers;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;

import static cn.hh.wechatkit.helper.WxConst.JSApiToken_GET_URL;

/**
 * Created this one by HMH on 2017/4/5.
 */

public class WxAPI_JsApi_Ticket_Api {

    private final static Logger logger = LoggerFactory.getLogger(WxAPI_JsApi_Ticket_Api.class);

    /**
     * 获取jssdk令牌
     * @param ACCESS_TOKEN 基础令牌
     * @return js令牌
     * @throws Wx_Exception_InvalidResponse 响应异常
     */
    public static WxToken_JsApiToken getToken(String ACCESS_TOKEN) {
        //组装url
        String url = JSApiToken_GET_URL.replace("ACCESS_TOKEN", ACCESS_TOKEN);
        //发送请求
        Response response = null;
        try {
            response = httpUtil.get(url);
        } catch (IOException e) {
            throw new Wx_Exception_InvalidResponse("接口请求出错", e);
        }
        if (response != null) {
            try {
                Headers headers = response.headers();
                String body = response.body().string();
                //解析字符串
                WxToken_JsApiToken wxJsApiToken = JSON.parseObject(body, WxToken_JsApiToken.class);
                if (wxJsApiToken != null) {
                    wxJsApiToken.setExpires_time(wxJsApiToken.getExpires_in() * 1000 + headers.getDate("date").getTime() - WxParam.expireTimeAhead);
                }
                return wxJsApiToken;
            } catch (IOException e) {
                throw new Wx_Exception_InvalidJsonParse("处理返回的JsApiToken发生错误\n",e);
            }
        }
        throw new Wx_Exception_InvalidResponse("没有收到响应，或者请求出错");
    }
}
